package com.example.springbootsfzy.filter;

import com.example.springbootsfzy.util.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.bcel.internal.generic.ACONST_NULL;
import com.sun.org.apache.bcel.internal.generic.DCONST;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebFilter
public class Filter_token implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        String URI = request.getRequestURI();
        System.out.println(URI);
        if(token!=null||URI.contains("/Login")||URI.contains("/file/download/byte/" )){
            System.out.println("验明身份,开始放行");
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            System.out.println(token);
            System.out.println("已被过滤器拦截!!!");
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            ServletOutputStream out = response.getOutputStream();
            R r = R.error2("请先登录后在进行操作");
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(r);
            out.write(json.getBytes());
            out.close();
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
